<template>
  <div class="edu-page-warp">
    <el-row :gutter="0">
      <el-col :span="12">
        <p class="section-title">任务编辑</p>
      </el-col>
      <el-col :span="12" class="text-right">
        <router-link to="/newerTasks">
          <el-button icon="el-icon-back">返回列表</el-button>
        </router-link>
      </el-col>
    </el-row>
    <el-card shadow="never" body-style="padding: 24px;">
      <el-form ref="newerTask" :model="newerTask" :rules="taskRules" label-position="left" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="年级" prop="year">
              <el-select v-model="newerTask.year" placeholder="请选择年级" style="width: 100%" @change="getPreTasks">
                <el-option v-for="item in options.grade" :key="item.value"
                           :label="item.label + '级'"
                           :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="培养层次">
              <el-select multiple v-model="newerTask.trainingLevel" placeholder="请选择培养层次" style="width: 100%">
                <el-option v-for="(item, index) in options.trainingLevel" :key="index" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="国际学生">
              <el-select v-model="newerTask.isStudentAbroad" placeholder="请选择" style="width: 100%">
                <el-option label="全部" value="2"></el-option>
                <el-option label="是" value="0"></el-option>
                <el-option label="否" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="必做">
              <el-switch
                v-model="newerTask.isRequired"
                active-value = '0'
                inactive-value = '1'>
              </el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="任务排序" prop="oreder">
              <el-input-number v-model="newerTask.oreder" placeholder="请输入任务排序" style="width: 100%"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="任务名称" prop="templateName">
              <el-input v-model="newerTask.templateName" placeholder="请输入任务名称" style="width: 100%"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="中文标语" prop="sloganInChinese">
              <el-input v-model="newerTask.sloganInChinese" placeholder="请输入中文标语" style="width: 100%"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="英文标语" prop="sloganInEnglish">
              <el-input v-model="newerTask.sloganInEnglish" placeholder="请输入英文标语" style="width: 100%"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="开始时间" prop="beginTime" style="width: 100%">
              <el-date-picker
                v-model="newerTask.beginTime"
                type="datetime"
                placeholder="选择开始时间"
                format="yyyy/MM/dd HH:mm:ss"
                value-format="timestamp"
                style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker
                v-model="newerTask.endTime"
                type="datetime"
                placeholder="选择结束时间"
                format="yyyy/MM/dd HH:mm:ss"
                value-format="timestamp"
                style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="使用外链" style="width: 100%">
              <el-switch
                v-model="newerTask.hasExtenalLink"
                active-value='1'
                inactive-value='0'
                @change="hasExtenalLink">
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="options.showLink">
            <el-form-item label="外链地址" prop="extenalLink">
              <el-input v-model="newerTask.extenalLink" placeholder="请输入外链地址" style="width: 100%"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="前置任务">
              <el-select multiple v-model="newerTask.templateIdList" placeholder="请选择前置任务" style="width: 100%">
                <el-option v-for="(item, index) in options.relyPredecessorsList" :key="index" :label="item.templateName"
                           :value="item.templateId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="允许手机">
              <el-switch
                v-model="newerTask.isPhone"
                active-value="1"
                inactive-value="0">
              </el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="18">
            <el-form-item label="任务简介" prop="introduction">
              <el-input type="textarea" :rows="4" v-model="newerTask.introduction" style="width: 100%;"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="任务配图">
              <el-upload
                class="avatar-uploader"
                action="/api/commonservice/obsfile/uploadimage"
                :data="{bucketname: 'face', folderpath: 'image'}"
                :on-success="handleAvatarSuccess"
                :on-error="handleAvatarError"
                :before-upload="beforeAvatarUpload"
                :show-file-list="false">
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item class="editor" label="任务详情" prop="details">
              <editor class="editor" :value="newerTask.details" v-model="newerTask.details" :setting="editorSetting" @input="(details)=> details = details"></editor>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="text-right">
          <el-button @click="resetForm('newerTask')">取消</el-button>
          <el-button type="primary" @click="submitForm('newerTask')">提交任务</el-button>
        </div>
      </el-form>
    </el-card>
  </div>

</template>
<script>
  import {
    createNewTask,
    getTasks,
    getTasksNoDetail,
    updateTask,
    getDicByType
  } from "common/src/api/welcomeService/taskTemplate";
  import {queryDic} from "common/src/api/dictionary";
  import {uploadimage} from "common/src/api/upload"
  import Bus from "common/src/utils/bus";
  import editor from "common/src/components/tinymce/editor";

  export default {
    name: "CreateNewerTask",
    components: {
      editor
    },
    data() {
      var validateEndTime = (rule, value, callback) => {
        let startTime = this.newerTask.beginTime;
        let endTime = value;
        if (startTime > endTime) {
          callback(new Error("结束时间不能小于开始时间"));
        } else {
          callback();
        }
      };
      const getGrade = (function() {
        let now = new Date().getFullYear();
        let years = [];
        for (let i = 0; i < 3; i++) {
          years.push({
            label: now + i,
            value: now + i
          });
        }
        return years;
      })();
      return {
        imageUrl: '',
        options: {
          trainingLevel: [],
          grade: getGrade,
          studentType: [],
          relyPredecessorsList: [],
          showLink: false
        },
        editorSetting: {
          height: 500
        },
        newerTask: {
          year: "",
          trainingLevel: [],
          isStudentAbroad: '2',
          oreder: "0",
          templateName: "",
          sloganInChinese: "",
          sloganInEnglish: "",
          beginTime: "",
          endTime: '',
          hasExtenalLink: "0",
          extenalLink: "",
          templateIdList: [],
          introduction: '',
          details: '',
          picturePath: '',
          isPhone: '0',
          isRequired: "1",
          templateType: "0"
        },
        taskRules: {
          year: [{required: true, message: "请选择年级", trigger: "change"}],
          templateName: [
            {required: true, message: "请输入名称", trigger: "blur"}
            // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
          ],
          oreder: [
            {required: true, message: "请输入任务顺序", trigger: "blur"}
            // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
          ],
          sloganInChinese: [
            {required: true, message: "请输入中文标语", trigger: "blur"}
            // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
          ],
          sloganInEnglish: [
            {required: true, message: "请输入英文标语", trigger: "blur"}
            // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
          ],
          beginTime: [
            {required: true, message: '请选择开始日期', trigger: 'change'}
          ],
          endTime: [
            {required: true, message: '请选择结束日期', trigger: 'change'},
            {validator: validateEndTime, trigger: "blur"}
          ],
          // details: [
          //   {required: true, message: "请输入任务详情", trigger: "blur"}
            // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
          // ]
        }
      };
    },
    methods: {
      submitForm(formName) {
        this.$refs[formName].validate(valid => {
          if (valid) {
            createNewTask(this.newerTask).then(res => {
              this.$refs[formName].resetFields();
              this.newerTask.trainingLevel = [];
              this.newerTask.templateIdList = [];
              this.$message({
                message: "任务创建成功",
                type: "success"
              });
              Bus.$emit("editSuccess", res);
              this.$router.push('/newerTasks');
            });
          } else {
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
        this.$router.push('/newerTasks');
      },
      hasExtenalLink(val) {
        this.options.showLink = val == 0 ? false : true;
        if (val == 0) {
          this.newerTask.extenalLink = "";
        }
      },
      handleAvatarSuccess(res, file) {
        this.newerTask.picturePath = res.data.file.objectkey;
        this.imageUrl = URL.createObjectURL(file.raw);
      },
      handleAvatarError(res, file) {
        this.$message({
          message: "任务配图上传上传失败",
          type: "error"
        })
      },
      beforeAvatarUpload(file) {
        const isAccept = ['image/jpeg','image/png'].includes(file.type) ;
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isAccept) {
          this.$message.error('上传图片只能是 JPG 或者 PNG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!');
        }
        return isAccept && isLt2M;
      },
      getPreTasks(val) {
        this.options.relyPredecessorsList = [];
        let query = {
          year: val,
          pageNum_: 1,
          pageSize_: 10000
        };
        getTasksNoDetail(query).then(allTasks=>{
          if (allTasks.data && allTasks.data.list.length > 0) {
            this.options.relyPredecessorsList = allTasks.data.list;
          }
        }).catch(res=>{});
      },
      initOptions() {
        // let data = {
      //   lang: this.$store.getters.language || "cn",
      //   type: "allChild",
      //   keys: ["X_PYCC"]
      // };
      // queryDic(data)
      //   .then(res => {
      //     if (res.code == 200) {
      //       this.fillSelect(res.data);
      //     }
      //   })
      //   .catch(res => {});
      getDicByType("X_PYCC").then(res =>{
        if(res.code == 200){
          this.fillSelect(res.data);
        }
      })
    },
      fillSelect(data) {
        this._fill("trainingLevel", data.X_PYCC);
      },
      _fill(type, data) {
        for (let key in data) {
          if(this.options[type]) {
            this.options[type].push({
              value: key,
              label: data[key]
            });
          }
        }
      }
    },
    mounted() {
      this.initOptions();
    }
  };
</script>
<style scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 80px;
    height: 80px;
    line-height: 80px;
    text-align: center;
    border: dashed 1px #d2d4d6;
  }

  .avatar {
    width: 80px;
    height: 80px;
    display: block;
  }
</style>
